package com.hualu.zks.httpclient;

import com.hualu.zks.CommonUtils.Globalparameters;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JProgressBar;

import com.hualu.lgproject.Model.File;
import com.hualu.lgproject.dao.FileDao;
import com.hualu.zks.GUI.JFrame_File;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

import com.hualu.zks.CommonUtils.CommonUtils;
import static com.hualu.zks.GUI.JFrame_File.nodeDao;

public class URLFileSaver implements Runnable {

    private static final int BUFFER_SIZE = 8 * 1024;
    ArrayList<File> fileList = new ArrayList<>();
    ArrayList<String> destUrlList = new ArrayList<>();
    ArrayList<Long> totalSizeList = new ArrayList<>();
    ArrayList<String> namePathList = new ArrayList<>();
    private JProgressBar jProgressBar;
    private JLabel jLabelDownInfo;
    private JLabel jLabelSpeedInfo;
    AsyncTaskCallback callback,callback1;
    private static Thread th;
    private static HttpURLConnection httpconn = null;
    private static FileOutputStream fos = null;
    private static BufferedInputStream bis = null;
    private static String downloadingFilePath = "";
    int sizeNow = 0;
    private static Thread dlSpeed;
    
    private URLFileSaver(ArrayList<File> fileList, ArrayList<String> destUrlList, ArrayList<String> namePathList, ArrayList<Long> totalSizeList, JProgressBar jProgressBar, JLabel jLabelDownInfo, JLabel jLabelSpeedInfo,AsyncTaskCallback callback, AsyncTaskCallback callback1) {
        this.jProgressBar = jProgressBar;
        this.namePathList = namePathList;
        this.destUrlList = destUrlList;
        this.totalSizeList = totalSizeList;
        this.jLabelDownInfo = jLabelDownInfo;
        this.jLabelSpeedInfo = jLabelSpeedInfo;
        this.fileList = fileList;
        this.callback = callback;
        this.callback1 = callback1;
    }

    public void run() {
            // TODO Auto-generated catch block

        saveToFile();
    }

    // 将网络文件保存为本地文件的方法
    public void saveToFile() {
        sizeNow = 0;
        int controlIndex = 0;

        URL url = null;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        FileDao fileDao = new FileDao();
        for (int i = 0; i < destUrlList.size(); i++) {
            try {
                sizeNow = 0;
                // 建立链接
                java.io.File f = new java.io.File(namePathList.get(i));
                if (f.exists()) {
//                    System.out.println("文件已存在，请先修改文件名再下载！");
                    JOptionPane.showMessageDialog(null, namePathList.get(i) + "文件已存在，请先修改文件名再下载！", "警告", JOptionPane.WARNING_MESSAGE);
                    callback.onComplete(-1);
                    return;
                }
                
                GetFileList getdata = new GetFileList();
                String[] s1 = destUrlList.get(i).split("/");
                String[] s2 = s1[2].split(":");
                System.out.println(s2[0]);
                //尝试获取一次 检测刻录机是否在休眠
                while(1==getdata.checkSleep(s2[0])){
                    try {
                        Thread.sleep(3*1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(JFrame_File.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                        
                url = new URL(destUrlList.get(i));
                httpconn = (HttpURLConnection) url.openConnection();
                httpconn.setConnectTimeout(5000);
                httpconn.setReadTimeout(5000);
                httpconn.connect();
                bis = new BufferedInputStream(httpconn.getInputStream());
                fos = new FileOutputStream(namePathList.get(i));
                System.out.println("正在获取链接[" + destUrlList.get(i) + "]的内容将其保存为文件[" + namePathList.get(i)
                        + "]");
                downloadingFilePath = namePathList.get(i);

                jLabelDownInfo.setText("00%_" + (i + 1) + "/" + destUrlList.size());
                // 保存文件
                dlSpeed = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int oldsize = 0;
                        while (true) {
                            jLabelSpeedInfo.setText(CommonUtils.bytes2kb(sizeNow-oldsize)+"/s");
                            oldsize = sizeNow;
                            try {
                                Thread.sleep(1*1000);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(URLFileSaver.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                });
                dlSpeed.start();
                while ((size = bis.read(buf)) != -1) {
                    fos.write(buf, 0, size);
                    sizeNow += size;
                    controlIndex++;
                    if (controlIndex >= 10 || sizeNow == totalSizeList.get(i)) {
                        controlIndex = 0;
                        float proportion = (float) sizeNow / totalSizeList.get(i);
                        int kI = (int) (100 * proportion);
                        jProgressBar.setValue(kI);
                        jLabelDownInfo.setText(kI + "%_" + (i + 1) + "/" + destUrlList.size());
                    }
                }
                dlSpeed.stop();
                fos.close();
                bis.close();
                httpconn.disconnect();
                if (fileList.get(i).getIsDownLoaded().equals("是")) {
                    continue;
                }
                fileDao.addFile(fileList.get(i));
                for (File fileBase : JFrame_File.fileList) {
                    if (fileList.get(i).getFileId().equals(fileBase.getFileId())) {
                        fileBase.setIsDownLoaded("是");
                        break;
                    }
                }
            } catch (MalformedURLException ex) {
                Logger.getLogger(URLFileSaver.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //System.err.println("\nHttpURLConnection的IO异常打印：" + ex.getMessage());
                if (ex.getMessage().contains("timed out")) {
                    JOptionPane.showMessageDialog(null, Globalparameters.strDownloadTimeOut, "警告", JOptionPane.WARNING_MESSAGE);
                    java.io.File f = new java.io.File(downloadingFilePath);
//                    System.out.println("要删除文件的是：" + downloadingFilePath);
                    if (f.exists()) {
                        f.delete();
                        callback1.onComplete(1);
                    } else {
//                        System.out.println("file is not exist!");
                    }
                    JFrame_File.jProgressBar1.setValue(0);
                    jLabelDownInfo.setText("0%_0/0");
                    jLabelSpeedInfo.setText("0KB/s");
                    callback1.onComplete(1);
                    return;
                }
                if(ex.getMessage().contains("No route to host")){
                    JOptionPane.showMessageDialog(null, Globalparameters.strNoRouteToHost, "警告", JOptionPane.WARNING_MESSAGE);
                    JFrame_File.jProgressBar1.setValue(0);
                    jLabelDownInfo.setText("0%_0/0");
                    jLabelSpeedInfo.setText("0KB/s");
                    callback1.onComplete(1);
                    return;
                }
            }
        }
        jProgressBar.setValue(0);
        jLabelDownInfo.setText("0%_0/0");
        jLabelSpeedInfo.setText("0KB/s");
        callback.onComplete(0);
    }

    /**
     * 下载单个文件
     */
    public static void downLoadFilelist(ArrayList<File> fileList, String path, boolean isMp4, JProgressBar jProgressBar, JLabel jLabelDownInfo, JLabel jLabelSpeedInfo,AsyncTaskCallback callback, AsyncTaskCallback callback1) {
        ArrayList<String> strUrlList = new ArrayList<>();
        ArrayList<Long> totalSizeList = new ArrayList<>();
        ArrayList<String> namePathList = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            if (isMp4 && fileList.get(i).getMp4Size() != null) {
                strUrlList.add(fileList.get(i).getMp4Url());
                totalSizeList.add(Long.valueOf(fileList.get(i).getMp4Size()));
                if (System.getProperty("os.name").equals("Mac OS X")) {
                    namePathList.add(path + "/" + fileList.get(i).getNameNotNull() + ".mp4");
                } else {
                    namePathList.add(path + "\\" + fileList.get(i).getNameNotNull() + ".mp4");
                }
            } else {
                strUrlList.add(fileList.get(i).getTtsUrl());
                totalSizeList.add(Long.valueOf(fileList.get(i).getTtsSize()));
                if (System.getProperty("os.name").equals("Mac OS X")) {
                    namePathList.add(path + "/" + fileList.get(i).getNameNotNull() + ".tts");
                } else {
                    namePathList.add(path + "\\" + fileList.get(i).getNameNotNull() + ".tts");
                }

            }
        }

        th = new Thread(new URLFileSaver(fileList,
                strUrlList, namePathList, totalSizeList, jProgressBar, jLabelDownInfo, jLabelSpeedInfo,callback,callback1));
        th.start();
    }

    public static void stopDownload() {
        try {
            th.stop();
            httpconn.disconnect();
            dlSpeed.stop();
            bis.close();
            fos.close();
            java.io.File f = new java.io.File(downloadingFilePath);
//            System.out.println("要删除文件的是：" + downloadingFilePath);
            if (f.exists()) {
                f.delete();
            } else {
//                System.out.println("file is not exist!");
            }
        } catch (IOException ex) {
            Logger.getLogger(URLFileSaver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
